import { useState, useRef, useEffect } from 'react';
import { Button, Layout, Input, List, Typography, Spin, Avatar, Modal } from 'antd';
import { SendOutlined, UserOutlined, RobotOutlined, DeleteOutlined, CopyOutlined, CheckOutlined } from '@ant-design/icons';
import styles from './deepAI.module.css';
import { useNavigate } from 'react-router-dom';

const { Header, Content, Footer } = Layout;
const { Title, Paragraph } = Typography;
const { TextArea } = Input;
const API_KEY = import.meta.env.VITE_DEEPSEEK_API_KEY;

function DeepseekAI() {
    const [messages, setMessages] = useState([]);
    const [inputValue, setInputValue] = useState('');
    const [loading, setLoading] = useState(false);
    const [copied, setCopied] = useState(false);
    const [streamingMessage, setStreamingMessage] = useState('');
    const messagesEndRef = useRef(null);
    const inputRef = useRef(null);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    };

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    useEffect(() => {
        inputRef.current?.focus();
    }, []);

    const handleSend = async () => {
        if (!inputValue.trim()) return;

        const userMessage = { role: 'user', content: inputValue };
        setMessages(prev => [...prev, userMessage]);
        setInputValue('');
        setLoading(true);
        setStreamingMessage('');

        try {
            if (!API_KEY) {
                throw new Error('未配置API密钥，请在.env文件中添加 VITE_DEEPSEEK_API_KEY');
            }
            
            const controller = new AbortController();
            const timeoutId = setTimeout(() => {
                controller.abort('请求超时');
            }, 60000);

            const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${API_KEY}`,
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    model: 'deepseek-ai/DeepSeek-V3',
                    messages: [
                        { role: 'system', content: '你是一个有帮助的AI助手。' },
                        ...messages,
                        { role: 'user', content: inputValue }
                    ],
                    stream: true,
                    temperature: 0.7,
                    max_tokens: 2000
                }),
                signal: controller.signal
            }).finally(() => {
                clearTimeout(timeoutId);
            });

            if (!response.ok) {
                const responseText = await response.text();
                console.error('错误响应内容:', responseText);

                let errorMessage;
                try {
                    const errorData = JSON.parse(responseText);
                    errorMessage = errorData.message || errorData.error || '未知错误';
                } catch {
                    errorMessage = responseText || response.statusText;
                }
                throw new Error(`请求失败 (${response.status}): ${errorMessage}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let fullResponse = '';

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value, { stream: true });
                const lines = chunk.split('\n').filter(line => line.trim() !== '');

                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        const data = line.substring(6);
                        if (data === '[DONE]') break;

                        try {
                            const parsed = JSON.parse(data);
                            const content = parsed.choices?.[0]?.delta?.content || '';
                            if (content) {
                                fullResponse += content;
                                setStreamingMessage(fullResponse);
                            }
                        } catch (e) {
                            console.error('解析流数据错误:', e);
                        }
                    }
                }
            }

            if (fullResponse) {
                setMessages(prev => [...prev, { role: 'assistant', content: fullResponse }]);
                setStreamingMessage('');
            }

        } catch (error) {
            console.error('错误详情:', {
                message: error.message,
                name: error.name,
                stack: error.stack
            });

            const errorMessage = error.name === 'AbortError'
                ? '请求超时，请稍后重试'
                : `错误: ${error.message}\n类型: ${error.name}\n状态码: ${error.status || '未知'}`;

            setMessages(prev => [...prev, {
                role: 'assistant',
                content: errorMessage
            }]);
        } finally {
            setLoading(false);
        }
    };

    const copyMessage = async (content) => {
        try {
            await navigator.clipboard.writeText(content);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        } catch (err) {
            console.error('复制失败:', err);
        }
    };

    const clearMessages = () => {
        Modal.confirm({
            title: '确认清空对话',
            content: '是否确认清空所有对话记录？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => setMessages([])
        });
    };

    const navigate = useNavigate();
    const handleMessageClick = () => {
        navigate('/message')
    }

    return (
        <Layout className={styles.layout}>
            <Header className={styles.header}>
                <div className={styles.headerContent}>
                    <Title level={3}
                        style={{ color: 'white', margin: 0 }}
                        onClick={handleMessageClick}>
                        AI 助手
                    </Title>
                    {messages.length > 0 && (
                        <Button
                            type="text"
                            icon={<DeleteOutlined />}
                            onClick={clearMessages}
                            style={{ color: 'white' }}
                        >
                            清空对话
                        </Button>
                    )}
                </div>
            </Header>
            <Content className={styles.content}>
                <div className={styles.chatContainer}>
                    {messages.length === 0 ? (
                        <div className={styles.welcomeScreen}>
                            <RobotOutlined className={styles.welcomeIcon} />
                            <Title level={2}>欢迎使用 DeepSeek AI 助手</Title>
                            <Paragraph>
                                您可以问我任何问题，我会尽力帮助您。
                            </Paragraph>
                            <div className={styles.featureList}>
                                <div className={styles.featureItem}>
                                    <SendOutlined />
                                    <span>快速响应</span>
                                </div>
                                <div className={styles.featureItem}>
                                    <CopyOutlined />
                                    <span>一键复制</span>
                                </div>
                                <div className={styles.featureItem}>
                                    <DeleteOutlined />
                                    <span>清空对话</span>
                                </div>
                            </div>
                        </div>
                    ) : (
                        <List
                            className={styles.messageList}
                            itemLayout="horizontal"
                            dataSource={messages}
                            renderItem={message => (
                                <List.Item
                                    style={{
                                        display: 'flex',
                                        alignItems: 'flex-start',
                                        justifyContent: 'flex-start',
                                        padding: '12px 0',
                                        border: 'none'
                                    }}
                                >
                                    <div className={styles.messageContent}>
                                        <Avatar
                                            icon={message.role === 'user' ? <UserOutlined /> : <RobotOutlined />}
                                            className={`${styles.avatar} ${message.role === 'user' ? styles.user : styles.assistant}`}
                                        />
                                        <div className={styles.messageBubbleWrapper}>
                                            <div className={`${styles.messageBubble} ${message.role === 'user' ? styles.userMessage : ''}`}>
                                                {message.role === 'user' ? (
                                                    <Paragraph style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
                                                        <span className={/^\d+$/.test(message.content.trim()) ? styles.numberDisplay : ''}>
                                                            {message.content}
                                                        </span>
                                                    </Paragraph>
                                                ) : (
                                                    <Paragraph style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
                                                        {message.content}
                                                    </Paragraph>
                                                )}
                                            </div>
                                            <div className={styles.messageActions}>
                                                <Button
                                                    type="text"
                                                    size="small"
                                                    icon={copied ? <CheckOutlined /> : <CopyOutlined />}
                                                    onClick={() => copyMessage(message.content)}
                                                    className={styles.actionButton}
                                                >
                                                    {copied ? '已复制' : '复制'}
                                                </Button>
                                            </div>
                                        </div>
                                    </div>
                                </List.Item>
                            )}
                        />
                    )}

                    {streamingMessage && (
                        <List.Item
                            style={{
                                display: 'flex',
                                alignItems: 'flex-start',
                                justifyContent: 'flex-start',
                                padding: '12px 0',
                                border: 'none'
                            }}
                        >
                            <div className={styles.messageContent}>
                                <Avatar
                                    icon={<RobotOutlined />}
                                    className={`${styles.avatar} ${styles.assistant}`}
                                />
                                <div className={styles.messageBubbleWrapper}>
                                    <div className={styles.messageBubble}>
                                        <Paragraph style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
                                            {streamingMessage}
                                            <Spin size="small" style={{ marginLeft: '8px' }} />
                                        </Paragraph>
                                    </div>
                                </div>
                            </div>
                        </List.Item>
                    )}

                    <div ref={messagesEndRef} />
                    
                </div>
                <div className={styles.inputArea}>
                    <div className={styles.inputContainer}>
                        <TextArea
                            ref={inputRef}
                            value={inputValue}
                            onChange={e => setInputValue(e.target.value)}
                            placeholder="请输入您的问题..."
                            autoSize={{ minRows: 1, maxRows: 6 }}
                            onPressEnter={(e) => {
                                if (!e.shiftKey) {
                                    e.preventDefault();
                                    handleSend();
                                }
                            }}
                            disabled={loading}
                            className={loading ? styles.inputDisabled : ''}
                        />
                        <Button
                            type="primary"
                            icon={<SendOutlined />}
                            onClick={handleSend}
                            loading={loading}
                            className={styles.sendButton}
                            disabled={!inputValue.trim()}
                        />
                    </div>
                    <div className={styles.inputHint}>
                        按 Enter 发送，Shift + Enter 换行
                    </div>
                </div>
            </Content>
        </Layout>
    );
}

export default DeepseekAI;
